package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Title  : 116. Populating Next Right Pointers in Each Node
 * Source : https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/description/
 * Author : XrazYang
 * Date   : 2024-04-09
 */
public class LeetCode_116 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Queue<Node> que = new ArrayDeque<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int size = que.size();
            Node pre = que.peek();
            for (int i = 0; i < size; i++) {
                Node node = que.poll();
                if (pre != node) {
                    pre.next = node;
                    pre = node;
                }
                if (node.left != null) {
                    que.offer(node.left);
                }

                if (node.right != null) {
                    que.offer(node.right);
                }
            }
        }
        return root;
    }
}
